<template>
  <div class="test-connection">
    <div class="container">
      <h1>🔧 连接测试工具</h1>
      
      <div class="test-section">
        <h3>后端服务状态</h3>
        <div class="status-card">
          <div class="status-item">
            <span>后端地址:</span>
            <span>{{ apiBaseUrl }}</span>
          </div>
          <div class="status-item">
            <span>连接状态:</span>
            <span :class="['status', backendStatus]">{{ backendStatusText }}</span>
          </div>
          <button @click="testBackendConnection" :disabled="testing">
            {{ testing ? '测试中...' : '测试连接' }}
          </button>
        </div>
      </div>

      <div class="test-section">
        <h3>SSE 连接测试</h3>
        <div class="test-form">
          <div class="form-group">
            <label>测试消息:</label>
            <input v-model="testMessage" placeholder="输入测试消息" />
          </div>
          <div class="form-group">
            <label>聊天室 ID:</label>
            <input v-model="testChatId" placeholder="输入聊天室 ID" />
          </div>
          <div class="button-group">
            <button @click="testLoveAppSSE" :disabled="testingSSE">
              {{ testingSSE ? '测试中...' : '测试恋爱大师 SSE' }}
            </button>
            <button @click="testManusSSE" :disabled="testingSSE">
              {{ testingSSE ? '测试中...' : '测试智能体 SSE' }}
            </button>
          </div>
        </div>
      </div>

      <div class="test-section">
        <h3>测试日志</h3>
        <div class="log-container">
          <div v-for="(log, index) in logs" :key="index" :class="['log-item', log.type]">
            <span class="log-time">{{ log.time }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
        <button @click="clearLogs" class="clear-btn">清除日志</button>
      </div>

      <div class="back-section">
        <button @click="goBack" class="back-btn">返回主页</button>
      </div>
    </div>
  </div>
</template>

<script>
import { connectLoveAppSSE, connectManusSSE, generateChatId } from '../services/api.js'

export default {
  name: 'TestConnection',
  data() {
    return {
      apiBaseUrl: 'http://localhost:8123/api',
      backendStatus: 'unknown',
      backendStatusText: '未知',
      testing: false,
      testingSSE: false,
      testMessage: '你好，这是一条测试消息',
      testChatId: generateChatId(),
      logs: [],
      eventSource: null
    }
  },
  mounted() {
    this.addLog('info', '测试页面已加载')
    this.testBackendConnection()
  },
  methods: {
    goBack() {
      this.$router.push('/')
    },
    
    addLog(type, message) {
      this.logs.push({
        type,
        message,
        time: new Date().toLocaleTimeString()
      })
      // 保持最多 50 条日志
      if (this.logs.length > 50) {
        this.logs.shift()
      }
    },
    
    clearLogs() {
      this.logs = []
    },
    
    async testBackendConnection() {
      this.testing = true
      this.addLog('info', '开始测试后端连接...')
      
      try {
        const response = await fetch(this.apiBaseUrl + '/health', {
          method: 'GET',
          mode: 'cors'
        })
        
        if (response.ok) {
          this.backendStatus = 'connected'
          this.backendStatusText = '已连接'
          this.addLog('success', '后端服务连接成功')
        } else {
          this.backendStatus = 'error'
          this.backendStatusText = '连接失败'
          this.addLog('error', `后端服务响应错误: ${response.status}`)
        }
      } catch (error) {
        this.backendStatus = 'error'
        this.backendStatusText = '连接失败'
        this.addLog('error', `后端服务连接失败: ${error.message}`)
      } finally {
        this.testing = false
      }
    },
    
    testLoveAppSSE() {
      this.testingSSE = true
      this.addLog('info', '开始测试恋爱大师 SSE 连接...')
      
      if (this.eventSource) {
        this.eventSource.close()
      }
      
      this.eventSource = connectLoveAppSSE(
        this.testMessage,
        this.testChatId,
        (data) => {
          this.addLog('success', `收到数据: ${data}`)
        },
        (error) => {
          this.addLog('error', `SSE 错误: ${error.message || error}`)
          this.testingSSE = false
        },
        () => {
          this.addLog('info', 'SSE 连接完成')
          this.testingSSE = false
        }
      )
    },
    
    testManusSSE() {
      this.testingSSE = true
      this.addLog('info', '开始测试智能体 SSE 连接...')
      
      if (this.eventSource) {
        this.eventSource.close()
      }
      
      this.eventSource = connectManusSSE(
        this.testMessage,
        (data) => {
          this.addLog('success', `收到数据: ${data}`)
        },
        (error) => {
          this.addLog('error', `SSE 错误: ${error.message || error}`)
          this.testingSSE = false
        },
        () => {
          this.addLog('info', 'SSE 连接完成')
          this.testingSSE = false
        }
      )
    }
  },
  
  beforeUnmount() {
    if (this.eventSource) {
      this.eventSource.close()
    }
  }
}
</script>

<style scoped>
.test-connection {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 10px;
}

.test-section h3 {
  margin-bottom: 15px;
  color: #333;
}

.status-card {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 5px;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
}

.status.connected {
  background: #d4edda;
  color: #155724;
}

.status.error {
  background: #f8d7da;
  color: #721c24;
}

.status.unknown {
  background: #fff3cd;
  color: #856404;
}

.test-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 600;
  color: #333;
}

.form-group input {
  padding: 10px;
  border: 2px solid #eee;
  border-radius: 5px;
  font-size: 14px;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
}

.button-group {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s;
}

button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.clear-btn {
  background: #dc3545;
}

.back-btn {
  background: #6c757d;
}

.log-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #eee;
  border-radius: 5px;
  padding: 10px;
  background: #f8f9fa;
}

.log-item {
  display: flex;
  gap: 10px;
  margin-bottom: 5px;
  padding: 5px;
  border-radius: 3px;
}

.log-item.info {
  background: #d1ecf1;
  color: #0c5460;
}

.log-item.success {
  background: #d4edda;
  color: #155724;
}

.log-item.error {
  background: #f8d7da;
  color: #721c24;
}

.log-time {
  font-size: 0.8rem;
  opacity: 0.7;
  min-width: 80px;
}

.log-message {
  flex: 1;
  word-break: break-all;
}

.back-section {
  text-align: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .container {
    padding: 20px;
  }
  
  .button-group {
    flex-direction: column;
  }
  
  .status-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>
